#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <sys/resource.h>
#include"logger.h"

#define			BACKLOG		13


int connect_server(char *listen_ip, int listen_port)
{

 	    int                      listen_fd, client_fd =-1;
        char                     buf[1024];
        struct sockaddr_in       serv_addr;
        int                      rv=-1;
        struct sockaddr_in       client_addr;
        socklen_t                len;
	    int			 on=1;

       listen_fd=socket(AF_INET,SOCK_STREAM,0);

        if(listen_fd<0)
        {
                printf("create socket failure:%s\n",strerror(errno));
                return -1;
        }
        printf("create fd[%d]",listen_fd);
	    setsockopt(listen_fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family=AF_INET;
        serv_addr.sin_port=htons(listen_port);

	 if( !listen_ip )
   	 {
      		  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);//监听0.0.0.0地址 socket只绑定端口让路由表决定传到哪个ip
   	 }
   	 else
  	 {
       		 if( inet_pton(AF_INET,listen_ip, &serv_addr.sin_addr) <= 0 )//将“点分十进制” －> “二进制整数”,若成功则为1，若输入不是有效的表达式则为0，若出错则为-1
	       	 {
        	    printf("Inet_pton() set listen IP address failure\n");
        	    rv = -2;
        	    goto cleanup;
        	 }
   	 }
        rv=bind(listen_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
        if(rv<0)
        {
                printf("bind failure:%s\n",strerror(errno));
                rv=-3;
		        goto cleanup;
        }
        printf("socket[%d]bind on port [%d] for all ip address ok\n",listen_fd,listen_port);
        if(listen(listen_fd,BACKLOG)<0)
	    {
		    printf("use bind() to bind the TCP socket failure:%s\n",strerror(errno));
		    rv=-4;
	    	goto cleanup;
	    }
	    cleanup:
		if(rv<0)
			close(listen_fd);
		else
			rv=listen_fd;
			return rv;
}

